<?php

namespace app\bll;

use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use support\Db;

/**
 * Admin主表
 */
class Admin
{

    /**
     * 根据UID查找管理员
     *
     * @param integer $uid uid
     * @return array 
     */
    public function findByUid(int $uid): array
    {
        $data =  Db::table('frame_admin')
            ->where('uid', '=', $uid)
            ->first();
        return $data === null ? [] : get_object_vars($data);
    }

    /**
     * 是否是管理员
     *
     * @param integer $uid
     * @return boolean|array
     */
    public function isAdmin(int $uid): bool|array
    {

        $info = $this->findByUid($uid);
        if (!$info) {
            return false;
        }

        return $info;
    }

    /**
     * 判断是否是系统超管
     *
     * @param integer $uid
     * @return boolean
     */
    public function isSystemAdmin(int $uid): bool
    {
        $admininfo = $this->isAdmin($uid);
        if (!$admininfo) {
            return false;
        }

        return $admininfo['issystem'] == 1;
    }


    /**
     * 管理员登录后的第一个链接
     *
     * @param array $admin 管理员信息
     * @return string 地址
     */
    public function firstUrl(array $admin): string
    {

        if ($admin['issystem'] == 1) {
            return '//' . rtrim(request()->host(), '/') . '/admin/index/index';
        }

        $bllSiteAdmin = new SiteAdmin();
        $sites        = $bllSiteAdmin->UserManageableSite($admin['id']);
        if (!$sites) {
            throw new Exception('无管理权限');
        }
        $sites        = array_column($sites, null, 'domain');

        $domain = '';
        $protocol = 'http://';
        $thisdomain = request()->host();

        if (key_exists($thisdomain, $sites)) {
            $protocol = $sites[$thisdomain]['protocol'];
            $domain   = $thisdomain;
        } else {
            reset($sites); // 将内部指针指向第一个元素
            $firstSite = current($sites);         // 获取当前元素（即第一个元素）
            $protocol  = $firstSite['protocol'];
            $domain    = $firstSite['domain'];
        }

        //非超级管理员
        //获取DOMAIN 对应的站点ID  再获取对应的角色
        //先获取站点角色
        $bllSiteAdmin  = new SiteAdmin();
        $siteadmininfo = $bllSiteAdmin->findByUid($admin['id'], $sites[$domain]['id']);

        if ($siteadmininfo['issuperadmin'] == 1) {
            //站点的超级管理员
            return '//' . rtrim($domain, '/') . '/admin/index/index';
        }

        $bllSiteRole   = new SiteRole();
        $auths         = $bllSiteRole->selAuthByIds(trim($siteadmininfo['roleids'], ','));
        if (isset($auths['menus'])) {
            foreach ($auths['menus'] as $menu) {
                if ($menu['url'] != '' && $menu['type'] == 0) {
                    return $protocol . rtrim($domain, '/') . $menu['url'];
                }
            }
        }


        return $protocol . rtrim($domain, '/') . '/admin/index/index';
    }

    /**
     * 分页查询
     *
     * @param string $username
     * @param string $phone
     * @param integer $pagesize
     * @return LengthAwarePaginator
     */
    public function paginator(
        string $username = '',
        string $phone = '',
        int $pagesize = 20
    ): LengthAwarePaginator {
        return  Db::table('frame_admin')
            ->leftJoin('frame_user', 'frame_user.id', '=', 'frame_admin.uid')
            ->leftJoin('frame_user_basicinfo', 'frame_user.id', '=', 'frame_user_basicinfo.uid')

            ->when($username != '', function ($query) use ($username) {
                $query->where('frame_user.username', 'like', '%' . $username . '%');
            })
            ->when($phone != '', function ($query) use ($phone) {
                $query->where('frame_user.phone', 'like', '%' . $phone . '%');
            })

            ->paginate(
                $pagesize,
                [
                    'frame_user.*',
                    'frame_admin.issystem',
                    'frame_user_basicinfo.birthday',
                    'frame_user_basicinfo.sex',
                    'frame_user_basicinfo.organcompanyid',
                    'frame_user_basicinfo.organpostid',

                ]
            );
    }
}
